<template>
    <nav class="navbar">
      <div class="logo">MyShop</div>
        <div class="search-bar">
            <input type="text" placeholder="搜索商品..." v-model="searchQuery">
            <button @click="performSearch">搜索</button>
        </div>
        <ul class="nav-items">
          <li>
            <router-link to="/home">购物车
              <span v-if="cartItemCount > 0" class="cart-badge">{{ cartItemCount }}</span>
            </router-link>
            <ul class="dropdown-menu">
              <li><a href="/payment">支付</a></li>
              <li><button @click="clearCart">清空</button></li>
            </ul>
          </li>
          <li><router-link to="/about">关于我们</router-link></li>
          <li><router-link to="/contact">联系</router-link></li>
          <li class="dropdown">
            <a href="#">账户</a>
            <ul class="dropdown-menu">
              <li><router-link to="/setting">设置</router-link></li>
              <li><button @click="logout">登出</button></li>
              <li><router-link to="/history">历史订单</router-link></li>
            </ul>
          </li>
        </ul>
    </nav>
</template>
  
<script>
import { ref, onMounted } from 'vue';
import axios from 'axios'
import instance from '@/utils/request'
import Swal from 'sweetalert2';

// 设置请求拦截器
axios.interceptors.request.use(config => {
    //console.log('Request URL:', config.url);
    //console.log('Request Method:', config.method);
    //console.log('Request Headers:', config.headers);
    //console.log('Request Body:', config.data);
    return config;
}, error => {
    console.error('Request Error:', error);
    return Promise.reject(error);
});
export default {
  data() {
    return {
      searchQuery: '', 
    };
  },
  setup() {
    const cartItemCount = ref(0);

    const fetchCartItemCount = async () => {
      try {
        const response = await instance.get('http://8.219.49.219:8080/onlineShopping/shoppingCar/count')
        cartItemCount.value = response.data.data;
      } catch (error) {
        console.error('Error fetching cart item count:', error);
      }
    };

    onMounted(() => {
      fetchCartItemCount();
    });

    return {
      cartItemCount,
      fetchCartItemCount
    };
  },
  methods: {
    async logout() {
      //console.log('Button clicked');
      try {
        const response = await fetch('http://8.219.49.219:8080/onlineShopping/user/logout', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          credentials: 'include'
        })
        .then(response => response.json())
        .then(data => {
            console.log(data)
            if (data.data == "用户未登录") {
                localStorage.removeItem('authToken');
                localStorage.removeItem('Bearer'); 
                Swal.fire({
                    icon: 'error',
                    title: '用户未登录',
                    text: '请登录后重试',
                    confirmButtonText: '去登录',
                    confirmButtonColor: '#3085d6', 
                    preConfirm: () => {
                    window.location.href = '/login';
                    }
                });    
            }
            if (data.data == "登出成功" && data.code == 200) {
                localStorage.removeItem('authToken');
                localStorage.removeItem('Bearer'); 
                window.location.href = '/login'  
            }
        })
        .catch(error => {
            console.log('Error:', error)
        });
      } catch (error) {
        console.error('Logout request failed', error);
      }
    },
    async clearCart() {
      try {
        const response = await instance.delete('http://8.219.49.219:8080/onlineShopping/shoppingCar/clear');
        location.reload();
      } catch (error) {
        console.error('Error clearing cart:', error);
        Swal.fire({
          icon: 'error',
          title: '清空购物车失败',
          text: '请稍后再试',
          confirmButtonText: '确定'
        });
      }
    },
    async performSearch() {
      //console.log(this.searchQuery)
      this.$emit('performSearch', this.searchQuery);
    }
    // async performSearch() {
    //   // 搜索
    //   try {
    //     const response = await instance.post('http://8.219.49.219:8080/onlineShopping/item/search', 
    //       {
    //         search : this.searchQuery
    //       }
    //     );
    //     const data = response.data.data;
    //   } catch (error) {
    //     console.error('Error Search:', error);
    //     Swal.fire({
    //       icon: 'error',
    //       title: '搜索失败',
    //       text: '请稍后再试',
    //       confirmButtonText: '确定'
    //     });
    //   }  
    // }
  }
}
</script>

<style scoped>
.navbar {
  background: linear-gradient(to right, #4A90E2, #50E3C2);
  color: white; 
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}


.logo {
  font-weight: bold;
  font-size: 1.5em;
}
.search-bar {
    margin-left: auto; 
    display: flex;
    align-items: center;
    border-radius: 5px;
    padding: 5px;
    transition: box-shadow 0.3s ease, transform 0.3s ease; 
}
.nav-items {
  list-style: none;
  display: flex;
  margin: 0;
  padding: 0;
}

.nav-items li {
  margin: 0 10px;
  position: relative;
}

.nav-items li a, .nav-items li button {
  color: white;
  text-decoration: none;
  padding: 10px 15px;
  border-radius: 5px;
  background-color: transparent;
  border: none;
  font-size: 1em;
  font-weight: normal;
  transition: background-color 0.3s, color 0.3s;
}

.nav-items li a:hover, .nav-items li button:hover {
  background-color: rgba(44, 62, 80, 0.8);
  color: #ECF0F1;
}

.dropdown-menu {
  display: none; 
  position: absolute; 
  top: calc(100% + 8px); 
  left: 0; 
  right: auto;
  background: linear-gradient(to right, #4A90E2, #50E3C2);
  border: 1px solid #2C3E50; 
  list-style-type: none; 
  padding: 0; 
  margin: 0; 
  width: 75px; 
  max-height: 300px; 
  overflow-y: auto; 
  box-sizing: border-box; 
  z-index: 1000; 
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); 
  border-radius: 4px; 
}

.dropdown {
  position: relative;
}

.dropdown-menu li {
  padding: 0;
  text-align: left;
}

.dropdown-menu li a, .dropdown-menu li button {
  text-decoration: none;
  color: white;
  display: block;
  padding: 10px;
  font-size: 1em;
  font-weight: normal;
  transition: background-color 0.3s;
}

.dropdown-menu li a:hover, .dropdown-menu li button:hover {
  background-color: rgba(44, 62, 80, 0.8); 
}

.nav-items li:hover .dropdown-menu {
  display: block;
}

@media (max-width: 768px) {
  .nav-items {
    display: none;
    flex-direction: column;
    width: 100%;
  }
  .nav-items li {
    text-align: center;
    padding: 10px 0;
  }
  .dropdown-menu {
    width: 100%;
    right: 0;
  }
}
.cart-badge {
  position: absolute;
  top: -10px; 
  right: -10px; 
  min-width: 20px; 
  height: 20px; 
  padding: 0 5px;
  border-radius: 10px; 
  background-color: #FF4136; 
  color: white;
  font-size: 12px; 
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); 
}

</style>




